
package action;

import beans.UserBean;
import db.User;
import javax.servlet.http.HttpSession;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontValidate;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.validation.Validate;

/**
 * Action log user.
 * @author Tomas CASTA
 */
@UrlBinding("/login.action")
public class LoginActionBean implements ActionBean {
    /** action context */
    private ActionBeanContext context;
    /** user login */
    @Validate(required = true, minlength = 2, maxlength = 20)
    private String login;
    /** user password */
    @Validate(required = true, minlength = 6)
    private String password;
    /** error message */
    private String errMsg;
    /** session */
    private HttpSession session;
    /** user */
    private User user;

    public ActionBeanContext getContext() {
        return context;
    }

    public void setContext(ActionBeanContext context) {
        this.context = context;
    }

    public UserBean getUserBean() {
         return (UserBean) context.getRequest().getSession().getAttribute("user");
    }

    public void setUserBean(UserBean user) {
        context.getRequest().getSession().setAttribute("user", user);
    }

    public String getLogin() {
        return login;
    }

    public void setErrMsg(String errMsg) {
        this.errMsg = errMsg;
    }

    public String getPassword() {
        return password;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getErrMsg() {
        return errMsg;
    }

    public HttpSession getSession() {
        return session;
    }

    public void setSession(HttpSession session) {
        this.session = session;
    }

    /**
     * Show form for login.
     * @return Resolution.
     */
    @DefaultHandler
    @DontValidate
    public Resolution show() {
        return new ForwardResolution("jsp/login.jsp");
    }
    /**
     * Log user.
     * @return Resolution
     */
    
    public Resolution login() {
        user = new User();
        user.setDb(this.context.getServletContext());

        /* Log user */
        boolean result = user.loginUser(login, password);
        errMsg = user.getErrMsg();
        
        /* OK */
        if (result) {
             this.setUserBean(user.getUserBean());           
             return new ForwardResolution("/index.action");
        }
        /* Error */
        else {
             return new ForwardResolution("jsp/login.jsp");
        }

        
    }
}
